package api

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"server/global"
	"server/internal/app/task"
	"server/internal/middleware"
	"server/internal/model"
	"server/internal/pkg/response"
	"server/internal/services"
	"server/utils/tools"
	"strconv"
)

// ConfigApi 常规管理管理
var ConfigApi = new(configApi)

type configApi struct {
	model.Config
}

// Router 路由
func (a configApi) Router(r *gin.RouterGroup) {
	api := r.Group("/config", middleware.LoginVerification, middleware.PermissionVerification)
	//验证权限
	api.GET("/index", a.detail)
	api.POST("/edit", a.edit)

	api2 := r.Group("/config", middleware.LoginVerification)
	api2.GET("/user_log", a.userLog)
	api2.GET("/get_user_info", a.getUserInfo)
	api2.POST("/user_edit", a.userEdit)
}

// Detail 单条
func (a configApi) detail(c *gin.Context) {
	group := c.Query("group")
	Db := global.GL_DB

	detail := configApi{}
	Db.Model(&detail).Where("`group` =?", group).First(&detail)
	info := make(map[string]any)
	json.Unmarshal([]byte(detail.Value), &info)
	response.SuccessData(c, info, "")
}

// Edit 编辑
func (a configApi) edit(c *gin.Context) {
	Db := global.GL_DB
	var param configApi
	info := make(map[string]any) //注意该结构接受的内容
	err := c.ShouldBindJSON(&info)
	if err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}
	str, _ := json.Marshal(info)
	if Db.Model(&param).Where("`group` = ?", info["group"]).Update("value", string(str)).Error == nil {
		response.Success(c, "", "修改成功")

	} else {
		response.Error(c, "修改失败")
	}

}

// List 列表
func (configApi) userLog(c *gin.Context) {
	Db := global.GL_DB          //初始化Db
	Db = services.Query(Db, c)  //查询构造
	Db = services.Paging(Db, c) //分页

	//快速搜索
	quickSearch := c.Query("quickSearch")
	if quickSearch != "" {
		Db = Db.Where("title like ?", "%"+quickSearch+"%")
	}

	list, total := services.SystemLog.GetList(Db)

	response.SuccessList(c, list, total)
}

// GetUserInfo 当前账号信息
func (a configApi) getUserInfo(c *gin.Context) {
	userInfo, _ := c.Get("userInfo")

	detail := services.User.GetById(userInfo.(model.User).ID)

	response.Success(c, detail, "")
}

// UserEdit 修改个人信息
func (a configApi) userEdit(c *gin.Context) {
	user := model.User{}
	if err := c.ShouldBindJSON(&user); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}
	userInfo, _ := c.Get("userInfo")
	user.ID = userInfo.(model.User).ID
	if user.Password != "" {
		user.Password = tools.GetMd5String(user.Password)
	}
	if _, err := services.User.Update(user); err == nil {
		response.Success(c, "", "编辑成功")
	} else {
		response.Error(c, "编辑失败")
	}
}

// 读取 定时任务状态
func (a configApi) taskStatus(c *gin.Context) {

	data := make(map[string]any)
	data["time"] = task.TaskStatus.Time
	data["status"] = task.TaskStatus.Status
	response.Success(c, "", "ok")
}

// 修改定时任务状态
func (a configApi) taskStatusEdit(c *gin.Context) {
	var param task.Status
	//注意该结构接受的内容
	err := c.ShouldBindJSON(&param)
	if err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": "参数错误", "err": err.Error()})
		response.Error(c, "参数错误", err.Error())
	}
	m, _ := strconv.Atoi(param.Time)
	if m <= 0 {
		response.Error(c, "间隔时间不能未0分钟", err.Error())
		return
	}

	if param.Status == "start" && task.TaskStatus.Status == "start" {
		response.Error(c, "定时任务正在运行，请关闭后重试", err.Error())
		return
	}
	task.TaskStatus.Time = param.Time
	if param.Status == "start" {
		task.Start()

	}

	if param.Status == "stop" {
		task.Stop()
		response.Success(c, "", "定时任务已关闭")
	}

}
